package com.nanfang51g3.ckz.ui.index;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import android.support.v4.content.ContextCompat;

import com.nanfang51g3.ckz.cache.CacheLoader;
import com.nanfang51g3.ckz.cache.NetworkCache;
import com.nanfang51g3.ckz.di.ApiModule;
import com.nanfang51g3.ckz.domain.IndexBean;
import com.nanfang51g3.ckz.domain.HttpResultBean;
import com.nanfang51g3.ckz.domain.ListIndexBean;
import com.nanfang51g3.ckz.domain.RightTypeBean;
import com.nanfang51g3.ckz.exec.Api2Exception;
import com.nanfang51g3.ckz.http.HttpResultFunc;
import com.nanfang51g3.ckz.http.RestApi;
import com.nanfang51g3.ckz.http.RxResultHelper;
import com.nanfang51g3.ckz.http.SchedulersCompat;
import com.nanfang51g3.ckz.http.SubscriberInterface;
import com.nanfang51g3.ckz.ui.base.BasePresenter;
import com.nanfang51g3.ckz.ui.fragment.home.HomeIndexFragment;
import com.nanfang51g3.ckz.utils.KLog;
import com.nanfang51g3.ckz.utils.MD5Utils;
import com.nanfang51g3.ckz.utils.SPUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import javax.inject.Inject;

import retrofit2.Retrofit;
import rx.Observable;
import rx.Subscription;
import rx.functions.Func1;

/**
 * Created by Administrator on 2016/4/13.
 */
public class IndexPresenter extends BasePresenter implements IndexContract.IndexActionsListener {

    private String message;
    private final RestApi _restApi;
    private final IndexContract.View mView;
    private boolean pullDown = false;

    /**
     * @see ApiModule#provideRetrofit()
     */
    @Inject
    Retrofit retrofit;

    @Inject
    public IndexPresenter(RestApi restApi, IndexContract.View mView) {
        KLog.i("TAG", "进入了...IndexPresenter");
        /**
         * @see ApiModule#provideRestApi(Retrofit)
         */
        this._restApi = restApi;
        KLog.i("TAG", _restApi == null ? "进入了...is null" : "进入了...not null");
        /**
         * @see IndexPresenterModule#provideIndexContractView()
         */
        this.mView = mView;
        KLog.i("TAG", mView == null ? "进入了...is null" : "进入了...not null");
    }

    private NetworkCache<ListIndexBean> networkCache;
    Observable observable;
    private static final String key = "data";

    @Override
    public void requestIndex(final int page, final int limit, final boolean pullDown) {
        this.pullDown = pullDown;
        KLog.i("TAG", retrofit == null ? "retrofit-1" : "retrofit-0");

        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("page", page + "");
        treeMap.put("limit", limit + "");
        final String sign = MD5Utils.getAccessToken(treeMap);
        String city = (String) SPUtil.get(mView.getContext(), "city", "");
        KLog.i("Evd", treeMap.toString() + "-" + sign + "-" + city);
        if (city.equals("")) {
            observable = _restApi.list(page, limit, sign);
        } else {
            observable = _restApi.list(page, limit, sign, city);
        }
        networkCache = new NetworkCache<ListIndexBean>() {
            @Override
            public Observable<ListIndexBean> get(String key, Class<ListIndexBean> cls) {
                return observable
                        .compose(SchedulersCompat.applyIoSchedulers())//线程
                        .compose(RxResultHelper.handleResult())//发数据...
                        .flatMap(new Func1<List<IndexBean>, Observable<? extends ListIndexBean>>() {
                            @Override
                            public Observable<? extends ListIndexBean> call(List<IndexBean> populars) {
                                ListIndexBean popular = new ListIndexBean(populars);
                                return Observable.just(popular);
                            }
                        });
            }
        };


        Subscription subscription;
        subscription = CacheLoader.getInstance(mView.getContext())
                .asDataObservable(key + sign, ListIndexBean.class, networkCache)
                .map(new Func1<ListIndexBean, List<IndexBean>>() {
                    @Override
                    public List<IndexBean> call(ListIndexBean listPopular) {
                        return listPopular.data;
                    }
                })
                .subscribe(new SubscriberInterface<List<IndexBean>>() {
                    /**
                     * 订阅开始时调用
                     */
                    @Override
                    public void onStart() {
                        super.onStart();
                        KLog.i("Evd", "onStart");
                        /**
                         * @see IndexActivity#showProgress()
                         */
                        mView.showProgress();

                    }

                    /**
                     * 请求完成
                     */
                    @Override
                    public void onCompleted() {
                        KLog.i("Evd", "onCompleted");
                        /**
                         * @see IndexActivity#dismissProgress()
                         */

                        mView.dismissProgress();

                    }

                    /**
                     * 异常
                     *
                     * @param msg
                     */
                    @Override
                    public void _onError(String msg) {
                        KLog.i("Evd", "_onError" + msg);
                        /**
                         * @see IndexActivity#dismissProgress()
                         */
                        mView.dismissProgress();
                        /**
                         * @see IndexActivity#showMessage(String)
                         *
                         */
                        mView.showMessage(msg, "");
                    }

                    /**
                     * 数据
                     *
                     * @param t
                     */
                    @Override
                    public void onNext(List<IndexBean> t) {
                        KLog.i("Evd", "onNext " + t.size());
                        /**
                         * @see IndexActivity#showSuccess(List, ArrayList, boolean, String)
                         */
                        mView.showSuccess(t, strings, pullDown, null);
                    }
                });
        addSubscrebe(subscription);

//        observable
//                .subscribeOn(Schedulers.io())
//                .unsubscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .map(new IndexResultFunc<List<IndexBean>>())
//                .subscribe(new SubscriberInterface<List<IndexBean>>() {
//                    /**
//                     * 订阅开始时调用
//                     */
//                    @Override
//                    public void onStart() {
//                        super.onStart();
//                        KLog.i("Evd", "onStart");
//                        /**
//                         * @see IndexActivity#showProgress()
//                         */
//                        mView.showProgress();
//
//                    }
//
//                    /**
//                     * 请求完成
//                     */
//                    @Override
//                    public void onCompleted() {
//                        KLog.i("Evd", "onCompleted");
//                        /**
//                         * @see IndexActivity#dismissProgress()
//                         */
//
//                        mView.dismissProgress();
//
//                    }
//
//                    /**
//                     * 异常
//                     *
//                     * @param msg
//                     */
//                    @Override
//                    public void _onError(String msg) {
//                        KLog.i("Evd", "_onError" + msg);
//                        /**
//                         * @see IndexActivity#dismissProgress()
//                         */
//                        mView.dismissProgress();
//                        /**
//                         * @see IndexActivity#showMessage(String)
//                         *
//                         */
//                        mView.showMessage(msg, "");
//                    }
//
//                    /**
//                     * 数据
//                     *
//                     * @param t
//                     */
//                    @Override
//                    public void onNext(List<IndexBean> t) {
//                        KLog.i("Evd", "onNext " + t.size());
//                        /**
//                         * @see IndexActivity#showSuccess(List, ArrayList, boolean, String)
//                         */
//                        mView.showSuccess(t, strings, pullDown, null);
//                    }
//                });

    }

    @Override
    public void requestIndex(int page, int limit, final boolean pullDown, final String tName) {
        this.pullDown = pullDown;
        KLog.e("Evd", retrofit == null ? "retrofit-1 来了" : "retrofit-0　来了");

        TreeMap<String, String> treeMap = new TreeMap<>();
        treeMap.put("page", page + "");
        treeMap.put("limit", limit + "");
        if (!tName.equals("全部")) {
            treeMap.put("tname", tName);
        }
        String sign = MD5Utils.getAccessToken(treeMap);
        String city = (String) SPUtil.get(mView.getContext(), "city", "");
        KLog.i("Evd", treeMap.toString() + "-" + sign + "-" + city);
        if (city.equals("") && !tName.equals("全部")) {
            observable = _restApi.listtnaem(page, limit, sign, tName);
        } else if (!city.equals("") && !tName.equals("全部")) {
            observable = _restApi.list(page, limit, sign, city, tName);
        } else {
            observable = _restApi.list(page, limit, sign, city);
        }
        networkCache = new NetworkCache<ListIndexBean>() {
            @Override
            public Observable<ListIndexBean> get(String key, Class<ListIndexBean> cls) {
                return observable
                        .compose(SchedulersCompat.applyIoSchedulers())//线程
                        .compose(RxResultHelper.handleResult())//发数据...
                        .flatMap(new Func1<List<IndexBean>, Observable<? extends ListIndexBean>>() {
                            @Override
                            public Observable<? extends ListIndexBean> call(List<IndexBean> populars) {
                                ListIndexBean popular = new ListIndexBean(populars);
                                return Observable.just(popular);
                            }
                        });
            }
        };


        Subscription subscription;
        subscription = CacheLoader.getInstance(mView.getContext())
                .asDataObservable(key + sign, ListIndexBean.class, networkCache)
                .map(new Func1<ListIndexBean, List<IndexBean>>() {
                    @Override
                    public List<IndexBean> call(ListIndexBean listPopular) {
                        return listPopular.data;
                    }
                })
                .subscribe(new SubscriberInterface<List<IndexBean>>() {
                    /**
                     * 订阅开始时调用
                     */
                    @Override
                    public void onStart() {
                        super.onStart();
                        KLog.i("Evd", "onStart");
                        /**
                         * @see IndexActivity#showProgress()
                         */
                        mView.showProgress();

                    }

                    /**
                     * 请求完成
                     */
                    @Override
                    public void onCompleted() {
                        KLog.i("Evd", "onCompleted");
                        /**
                         * @see IndexActivity#dismissProgress()
                         */

                        mView.dismissProgress();

                    }

                    /**
                     * 异常
                     *
                     * @param msg
                     */
                    @Override
                    public void _onError(String msg) {
                        KLog.i("Evd", "_onError" + msg);
                        /**
                         * @see IndexActivity#dismissProgress()
                         */
                        mView.dismissProgress();
                        /**
                         * @see IndexActivity#showMessage(String)
                         *
                         */
                        /**
                         * @see HomeIndexFragment#showMessage(String)
                         *
                         */
                        mView.showMessage(msg, tName);
                    }

                    /**
                     * 数据
                     *
                     * @param t
                     */
                    @Override
                    public void onNext(List<IndexBean> t) {
                        KLog.i("Evd", "onNext " + t.size());
                        /**
                         * @see IndexActivity#showSuccess(List, ArrayList, boolean, String)
                         * @see HomeIndexFragment#showSuccess(List, ArrayList, boolean, String)
                         */
                        mView.showSuccess(t, strings, pullDown, tName);
                    }
                });


//        observable
//                .subscribeOn(Schedulers.io())
//                .unsubscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .map(new IndexResultFunc<List<IndexBean>>())
//                .subscribe(new SubscriberInterface<List<IndexBean>>() {
//                    /**
//                     * 订阅开始时调用
//                     */
//                    @Override
//                    public void onStart() {
//                        super.onStart();
//                        KLog.i("Evd", "onStart");
//                        /**
//                         * @see IndexActivity#showProgress()
//                         */
//                        mView.showProgress();
//
//                    }
//
//                    /**
//                     * 请求完成
//                     */
//                    @Override
//                    public void onCompleted() {
//                        KLog.i("Evd", "onCompleted");
//                        /**
//                         * @see IndexActivity#dismissProgress()
//                         */
//
//                        mView.dismissProgress();
//
//                    }
//
//                    /**
//                     * 异常
//                     *
//                     * @param msg
//                     */
//                    @Override
//                    public void _onError(String msg) {
//                        KLog.i("Evd", "_onError" + msg);
//                        /**
//                         * @see IndexActivity#dismissProgress()
//                         */
//                        mView.dismissProgress();
//                        /**
//                         * @see IndexActivity#showMessage(String)
//                         *
//                         */
//                        /**
//                         * @see HomeIndexFragment#showMessage(String)
//                         *
//                         */
//                        mView.showMessage(msg, tName);
//                    }
//
//                    /**
//                     * 数据
//                     *
//                     * @param t
//                     */
//                    @Override
//                    public void onNext(List<IndexBean> t) {
//                        KLog.i("Evd", "onNext " + t.size());
//                        /**
//                         * @see IndexActivity#showSuccess(List, ArrayList, boolean, String)
//                         * @see HomeIndexFragment#showSuccess(List, ArrayList, boolean, String)
//                         */
//                        mView.showSuccess(t, strings, pullDown, tName);
//                    }
//                });

    }

    ArrayList<RightTypeBean> strings = new ArrayList<>();

    class IndexResultFunc<T> extends HttpResultFunc<T> {
        @Override
        public T call(HttpResultBean<T> httpResult) {
            KLog.i("Evd", httpResult == null ? "1-" : "0-" + httpResult.getCode() + "-" + httpResult.getInfo() + "-" + "-" + httpResult.getTypelist().length);
            if (pullDown == true) {
                int size = httpResult.getTypelist().length;
                strings.add(0, new RightTypeBean("全部", true));
                for (int i = 0; i < size; i++) {
                    RightTypeBean typeBean = new RightTypeBean();
                    typeBean.setSelect(false);
                    typeBean.setTypeName(httpResult.getTypelist()[i]);
                    strings.add(typeBean);

                }
            }
            if (httpResult.getCode() == 2) {
                throw new Api2Exception("没有更多了");
            }
            message = httpResult.getInfo();
            return httpResult.getData();
        }

    }

    //是GPS功能的;
    boolean isGPSEnabled;
    //在网络启用;
    boolean isNetworkEnabled;
    //位置服务可用;
    boolean locationServiceAvailable;
    //位置
    private Location location;
    private static Geocoder geocoder;    //此对象能通过经纬度来获取相应的城市等信息
    //用于获取Location对象，以及其他
    private LocationManager locationManager;


    @Override
    public void initLocation(Context context, LocationServerListener locationListener) {
        if (Build.VERSION.SDK_INT >= 23 &&
                //GPS定位信息  WiFi或移动基站经纬度信息
                ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            KLog.e("Build.VERSION.SDK_INT >= 23");
            return;
        }
        geocoder = new Geocoder(context);//地理编码
        //实例化一个LocationManager对象
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);    //高精度
        criteria.setAltitudeRequired(false);    //不要求海拔
        criteria.setBearingRequired(false);    //不要求方位
        criteria.setCostAllowed(false);    //不允许有话费
        criteria.setPowerRequirement(Criteria.POWER_LOW);    //低功耗
        //通过最后一次的地理位置来获得Location对象
        try {
            // network status and Get GPS
            this.isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            this.isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            KLog.e("isGPSEnabled" + isGPSEnabled);
            KLog.e("isNetworkEnabled" + isNetworkEnabled);
            if (isNetworkEnabled) {
                //网络位置提供商的名称，时间毫秒，距离米.
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 50,
                        locationListener);
                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    updateCoordinates();
                }
            }//end if
            if (isGPSEnabled) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 50,
                        locationListener);

                if (locationManager != null) {
                    location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    updateCoordinates();
                }
            }
            //移除监听器，在只有一个widget的时候，这个还是适用的
//            locationManager.removeUpdates(locationListener);
        } catch (Exception e) {
            e.printStackTrace();
            KLog.i("e=" + e.toString());
        }
    }

    public void updateCoordinates() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                updateWithNewLocation(location);
            }
        }).start();
    }

    @Override
    public void updateWithNewLocation(Location location) {
        KLog.e("EEE", "updateWithNewLocation" + new java.util.Date(System.currentTimeMillis()));
        String mcityName = "";
        String value = "";
        double lat = 0;
        double lng = 0;
        List<Address> addList = null;
        if (location != null) {
            lat = location.getLatitude();
            lng = location.getLongitude();
        } else {
            KLog.e("location==null 无法获取地理信息");
        }
        try {
            //纬度，经度，最大量
            addList = geocoder.getFromLocation(lat, lng, 1);    //解析经纬度
            KLog.e("addList=" + addList.size());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            KLog.e("e=" + e.toString());
        }
        if (addList != null && addList.size() > 0) {
            for (int i = 0; i < addList.size(); i++) {
                Address add = addList.get(i);
                mcityName += add.getLocality();
            }
        }
        if (mcityName.length() != 0) {
            value = mcityName.substring(0, (mcityName.length() - 1));
            SPUtil.putAndApply(mView.getContext(), "city", value);//bug
            /**
             * @see IndexActivity#showLocationValue(String)
             */
            mView.showLocationValue(value);
        } else {
            value = mcityName;
            /**
             * @see IndexActivity#showLocationValue(String)
             */
            mView.showLocationValue(value);
            SPUtil.putAndApply(mView.getContext(), "city", value);
        }
    }

    public static String GetAddr(String latitude, String longitude) {
        String addr = "";
        String url = String.format(
                "http://ditu.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s",
                latitude, longitude);
        URL myURL = null;
        URLConnection httpsConn = null;
        try {

            myURL = new URL(url);
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }

        try {

            httpsConn = (URLConnection) myURL.openConnection();

            if (httpsConn != null) {
                InputStreamReader insr = new InputStreamReader(
                        httpsConn.getInputStream(), "UTF-8");
                BufferedReader br = new BufferedReader(insr);
                String data = null;
                if ((data = br.readLine()) != null) {
                    String[] retList = data.split(",");
                    if (retList.length > 2 && ("200".equals(retList[0]))) {
                        addr = retList[2];
                    } else {
                        addr = "";
                    }
                }
                insr.close();
            }
        } catch (IOException e) {

            e.printStackTrace();
            return null;
        }
        return addr;
    }

    @Override
    public void loginSuccess(String message) {

    }

    @Override
    public void loginError(String message) {

    }

}